package com.tbynet.jwp.service.task;

import com.jfinal.log.Log;
import com.tbynet.jwp.service.dto.response.TermResponse;
import com.tbynet.jwp.service.support.TermCacheManager;
import com.tbynet.jwp.service.support.TermResponseBuilder;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * 缓存清理任务
 * 负责异步清理分类项相关缓存
 */
public class TermCacheCleanTask implements Callable<TermResponse.CacheCleanResult> {

    private static final Log log = Log.getLog(TermCacheCleanTask.class);

    /** 要清理的分类项ID列表 */
    private final List<BigInteger> termIds;
    /** 分类法类型 */
    private final String taxonomy;
    /** 缓存管理器 */
    private final TermCacheManager cacheManager;

    /**
     * 构造函数
     *
     * @param termIds 分类项ID列表
     * @param taxonomy 分类法类型
     * @param cacheManager 缓存管理器
     */
    public TermCacheCleanTask(List<BigInteger> termIds, String taxonomy,
                              TermCacheManager cacheManager) {
        this.termIds = termIds != null ?
                Collections.unmodifiableList(new ArrayList<>(termIds)) :
                Collections.emptyList();
        this.taxonomy = taxonomy;
        this.cacheManager = cacheManager;
    }

    /**
     * 执行缓存清理任务
     *
     * @return 缓存清理结果
     */
    @Override
    public TermResponse.CacheCleanResult call() {
        // 参数验证
        if (termIds.isEmpty()) {
            return TermResponseBuilder.createFailedResult("清理分类项缓存参数错误", taxonomy);
        }

        try {
            // 清理具体分类项缓存
            cacheManager.batchRemoveTermCache(termIds, taxonomy);

            // 清理层级缓存
            cacheManager.removeHierarchyCache(taxonomy, null);

            return TermResponseBuilder.createSuccessResult(termIds.size(), termIds, taxonomy);

        } catch (Exception e) {
            log.error("缓存清理过程中发生异常", e);
            return TermResponseBuilder.createFailedResult("缓存清理过程中发生异常: " + e.getMessage(), taxonomy);
        }
    }


}